import cv2
import numpy as np


def imagesToVideo(video_duration, image_duration, imageCoverBytes, image_bytes_list, video_size, save_path):
    """
    图片转视频，图片数量不够则轮播
    @param imageCoverBytes: 封面
    @param image_bytes_list: image_bytes_list
    @param save_path: 视频保存地址
    @param video_duration: 所需视频时长(s)
    @param image_duration: 每张图片播放时长(s)
    @param video_size: 视频尺寸
    """

    # 图片尺寸
    image_size = video_size

    # 利用有限的图片制作符合视频时长的图片集（图片轮播）
    images = [imageCoverBytes]
    now_video_duration = image_duration
    while now_video_duration < video_duration:
        for image in image_bytes_list:
            if now_video_duration >= video_duration:
                break
            images.append(image)
            now_video_duration += image_duration

    # 制作视频
    fourcc = cv2.VideoWriter_fourcc(*'MP4V')
    video = cv2.VideoWriter(save_path, fourcc, 1.0, image_size)
    for image_bytes in images:
        img_np = np.frombuffer(image_bytes, dtype=np.uint8)
        image = cv2.imdecode(img_np, cv2.IMREAD_COLOR)
        # 修改图片尺寸
        image = cv2.resize(image, image_size)
        # 将图片写入视频
        for _ in range(image_duration):
            video.write(image)
    # 关闭视频流
    cv2.destroyAllWindows()
    video.release()
